package ru.firststeps.speedtest;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.text.TextUtils;

public class DataProvider extends ContentProvider {
    public static final String DB_DATA = "data.db";
    public static final Uri CONTENT_URI = Uri
            .parse("content://ru.firststeps.speedtest.dataprovider/measure");
    private SQLiteDatabase db;

    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        int retVal = db.delete(DataDBHelper.TABLE_NAME, where, whereArgs);
        getContext().getContentResolver().notifyChange(uri, null);
        return retVal;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long rowid = db.insert(DataDBHelper.TABLE_NAME, DataDBHelper.SPEED,
                values);
        Uri insertUri = null;
        if (rowid > 0) {
            insertUri = ContentUris.withAppendedId(uri, rowid);
            getContext().getContentResolver().notifyChange(insertUri, null);
        }
        return insertUri;
    }

    @Override
    public boolean onCreate() {
        db = new DataDBHelper(getContext()).getWritableDatabase();
        return (db == null) ? false : true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        String orderBy = null;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = DataDBHelper.SPEED;
        } else {
            orderBy = sortOrder;
        }

        Cursor cursor = db.query(DataDBHelper.TABLE_NAME, projection,
                selection, selectionArgs, null, null, orderBy);
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        int retVal = db.update(DataDBHelper.TABLE_NAME, values, selection,
                selectionArgs);
        getContext().getContentResolver().notifyChange(uri, null);
        return retVal;
    }

}
